package cn.cdzdjd.config;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.constant.UniappPlatform;
import cn.cdzdjd.util.JsonUtils;
import cn.cdzdjd.vo.DouYinUserVo;
import cn.cdzdjd.vo.UserSessionVo;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class PlatformApi {
	@Resource
	private MiniProgramConfiguration miniProgramConfig;
	@Resource
	private RestTemplate restTemplate;

	public UserSessionVo code2session(String code, String provider) {
		MiniProgramProperties properties = null;
		if (provider.equals(UniappPlatform.dy.getProvider())) {
			properties = miniProgramConfig.getDouyin();
		}
		if (provider.equals(UniappPlatform.wx.getProvider())) {
			properties = miniProgramConfig.getWeixin();
		}
		Map<String, String> map = new HashMap<>();
		map.put("appid", properties.getAppid());
		map.put("secret", properties.getSecret());
		UserSessionVo user = null;
		if (provider.equals(UniappPlatform.wx.getProvider())) {
			map.put("js_code", code);
			map.put("grant_type", "authorization_code");
			String response = restTemplate.getForObject(properties.getCode_2_session(), String.class, map);
			log.info("微信登录返回数据为{}", response);
			user = JsonUtils.parseObject(response, UserSessionVo.class);
		}
		if (provider.equals(UniappPlatform.dy.getProvider())) {
			map.put("code", code);
			HttpEntity<Map<String, String>> requestEntity = new HttpEntity<Map<String, String>>(map);
			ResponseEntity<String> responseEntity = restTemplate.postForEntity(properties.getCode_2_session(),
					requestEntity, String.class);
			String response = responseEntity.getBody();
			DouYinUserVo douyinUser = JsonUtils.parseObject(response, DouYinUserVo.class);
			user = douyinUser.getData();
		}
		return user;
	}
}
